const xss = require('xss');
const { exec, escape } = require('../db/mysql');

// 根据作者 或者关键字 查询
const getList = (author, keyword) => {
    let sql = `select * from blogs where 1=1 `
    if (author) {
        sql += `and author='${author}'`
    }
    if (keyword) {
        sql += `and title like %'${keyword}'%`
    }
    sql += `order by createtime desc;`
    // 返回的是一个 promise
    return exec(sql);
    // return [
    //     {
    //         id: 1,
    //         title: '标题1',
    //         content: '内容1',
    //         createTiem: 1609159854675,
    //         author: 'kruup'
    //     }
    // ]

}

const getDetail = (id) => {

    let sql = `select * from blogs where id='${id}';`
    return exec(sql).then(rows => {
        return rows[0];
    });
    // return {
    //     id: 2,
    //     title: '标题2',
    //     content: '内容2',
    //     createTiem: 1609159854676,
    //     author: 'kruup2'
    // }
}

const newBlog = (blogData = {}) => {
    // blogData 是一个博客对象  包含 title content 属性、
    let titel = xss(blogData.title)
    titel = escape(titel);
    const content = escape(blogData.content);
    const author = escape(blogData.author);
    const createtime = Date.now();
    let sql = `insert into blogs(title,content,createtime,author) 
    values (${titel},${content},'${createtime}',${author}) `;
    return exec(sql).then(insertData => {
        return {
            id: insertData.insertId
        };
    });
    // return {
    //     id: 3
    // }
}

const updateBlog = (id, blogData) => {
    // 根据id 更新 内容
    const titel = escape(blogData.title);
    const content = escape(blogData.content);
    let sql = `update blogs set title=${titel},content=${content} where id='${id}'`;
    return exec(sql).then(updateData => {
        if (updateData.affectedRows > 0) {
            return true;
        }
        return false;
        // return {
        //     id:insertData.insertId
        // };
    })

    // blogData 需要更新的内容  包含title content 属性
    //return true;
}

const deleteBlog = (id, author) => {
    //根据id 删除 内容
    author = escape(author)

    let sql = `delete from blogs where id='${id}' and author=${author}`;
    return exec(sql).then(delData => {
        if (delData.affectedRows > 0) {
            return true;
        }
        return false;
    })
}

module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    deleteBlog
}